package ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.Loader;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.socks.library.KLog;
import com.sxpjyy.monkey.mobilenurse.R;

import java.util.ArrayList;
import java.util.List;

import broadcastreceiver.UpdateReceiver;
import butterknife.BindView;
import butterknife.ButterKnife;
import mytools.CurrentVersion;
import mytools.MyBaseActivity;
import mytools.MyServiceUtil;
import objects.LoginQuery;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.UpdateService;

import static android.Manifest.permission.READ_CONTACTS;

/**
 * A login screen that offers login via account/password.
 */
public class LoginActivity extends MyBaseActivity implements LoaderCallbacks<Cursor>, Button.OnClickListener {

    private static final int REQUEST_READ_CONTACTS = 0;
//    private UserLoginTask mAuthTask = null;

    // UI references.
    @BindView(R.id.account)
    AutoCompleteTextView mAccountView;
    @BindView(R.id.password)
    EditText mPasswordView;
    @BindView(R.id.login_progress)
    View mProgressView;
    @BindView(R.id.login_form)
    View mLoginFormView;
    @BindView(R.id.account_sign_in_button)
    Button mAccountSignInButton;

    private boolean isNetworkAvailable = false;
    private boolean hasSBXH = false;

    private UpdateReceiver updateReceiver = null;//更新广播接收器
    private Intent serviceIntent;//更新Intent
//    private int newVerCode;//新版本版本号
//    private String newVerName;//新版本版本名称

    private static String WriteAvaliableStoragePath = null;//更新apk存储路径


//    private List<User> mUserList;

    private Call<String> sbxhCall;
    private Call<String> loginQueryCall;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        populateAutoComplete();

        mPasswordView.setOnEditorActionListener((textView, id, keyEvent) -> {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        });
        mAccountSignInButton.setOnClickListener(this);
        updateReceiver = new UpdateReceiver(this);
        IntentFilter intentFilter = new IntentFilter("updatebroadcast");
        this.registerReceiver(updateReceiver, intentFilter);
        //启动更新service
        serviceIntent = new Intent(this, UpdateService.class);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.account_sign_in_button:
//                if (isNetworkAvailable && hasSBXH) {
                if (isNetworkAvailable) {
                    attemptLogin();
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), "网络连接未可用或服务器连接失败！", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        String account = getMySharedPreferences().getString("account", "");
        String password = getMySharedPreferences().getString("password", "");
        if (!account.equals("")) {
            mAccountView.setText(account);
        }
        if (!password.equals("")) {
            mPasswordView.setText(password);
        }
        startService(serviceIntent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (sbxhCall != null && sbxhCall.isExecuted()) {
            sbxhCall.cancel();
            sbxhCall = null;
        }
        if (loginQueryCall != null && loginQueryCall.isExecuted())
            stopService(serviceIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(updateReceiver);
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    private void populateAutoComplete() {
        if (!mayRequestContacts()) {
            return;
        }
        getLoaderManager().initLoader(0, null, this);
    }

    private boolean mayRequestContacts() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return true;
        }
        if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
            return true;
        }
        if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
            Snackbar.make(mAccountView, R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                    .setAction(android.R.string.ok, v -> requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS));
        } else {
            requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
        }
        return false;
    }

    /**
     * Callback received when a permissions request has been completed.
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                populateAutoComplete();
            }
        }
    }

    /**
     * Attempts to sign in or register the account specified by the login form.
     * If there are form errors (invalid account, missing fields, etc.), the
     * errors are presented and no actual login attempt is made.
     */
    private void attemptLogin() {
//        if (mAuthTask != null) {
//            return;
//        }
        // Reset errors.
        mAccountView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        String account = mAccountView.getText().toString();
        String password = mPasswordView.getText().toString();

        boolean cancel = false;
        View focusView = null;

        // Check for a valid password, if the user entered one.
        if (TextUtils.isEmpty(password)) {
//            mPasswordView.setError(getString(R.string.error_invalid_password));
//            focusView = mPasswordView;
//            cancel = true;
            password = "";
        }

        // Check for a valid email address.
        if (TextUtils.isEmpty(account)) {
            mAccountView.setError(getString(R.string.error_field_required));
            focusView = mAccountView;
            cancel = true;
        }
//        else if (!isEmailValid(account)) {
//            mAccountView.setError(getString(R.string.error_invalid_email));
//            focusView = mAccountView;
//            cancel = true;
//        }
        if (cancel) {
            // There was an error; don't attempt login and focus the first
            // form field with an error.
            focusView.requestFocus();
        } else {
            // Show a progress spinner, and kick off a background task to
            // perform the user login attempt.
            showProgress(true);
            LoginQuery loginQuery = new LoginQuery(account, password);
            Gson gson = new Gson();
            String jsonString = gson.toJson(loginQuery);
            doLoginQuery(jsonString);

        }
    }


    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(this,
                // Retrieve data rows for the device user's 'profile' contact.
                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,

                // Select only email addresses.
                ContactsContract.Contacts.Data.MIMETYPE +
                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                .CONTENT_ITEM_TYPE},

                // Show primary email addresses first. Note that there won't be
                // a primary email address if the user hasn't specified one.
                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        List<String> accounts = new ArrayList<>();
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            accounts.add(cursor.getString(ProfileQuery.ADDRESS));
            cursor.moveToNext();
        }
        addAccountsToAutoComplete(accounts);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {

    }

    private void addAccountsToAutoComplete(List<String> accountCollection) {
        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
        ArrayAdapter<String> adapter =
                new ArrayAdapter<>(LoginActivity.this,
                        android.R.layout.simple_dropdown_item_1line, accountCollection);

        mAccountView.setAdapter(adapter);
    }

    private interface ProfileQuery {
        String[] PROJECTION = {
                ContactsContract.CommonDataKinds.Email.ADDRESS,
                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
        };

        int ADDRESS = 0;
//        int IS_PRIMARY = 1;
    }

    public void setNetworkAvailable(boolean networkAvailable) {
        isNetworkAvailable = networkAvailable;
    }

    /**
     * 更新提示对话框
     */
    public void showUpdateDialog(int newVerCode, String newVerName) {
        cancelProgressDialog();
        String message = "";
        final Intent intent = new Intent("toUpdateService");
        message += "当前版本：" + CurrentVersion.getVerName(this) + "\n";
        message += "版本号：" + CurrentVersion.getVerCode(this) + "\n";
        message += "发现新版本：" + newVerName + "\n";
        message += "版本号：" + newVerCode + "\n";
        message += "是否更新？";
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("确定", (dialog12, which) -> {
                    if (WriteAvaliableStoragePath != null && !WriteAvaliableStoragePath.equals("")) {
                        intent.putExtra("toservice", 0x11);
                        sendBroadcast(intent);
                        dialog12.dismiss();
                        showProgressDialog("下载中");
                    } else {
                        Toast.makeText(LoginActivity.this, "SD卡不可写入！", Toast.LENGTH_LONG).show();
                    }
                }).setNegativeButton("取消", (dialog1, which) -> dialog1.dismiss()).create();
        dialog.show();
    }

    public void doGetSBXH(String deviceSerial, String MAC_ADD) {
        sbxhCall = MyServiceUtil.getSBXHCall(deviceSerial, MAC_ADD);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                String result = response.body();
                if (result != null) {
                    hasSBXH = true;
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "获取设备信息出错，无法登陆！", Toast.LENGTH_SHORT).show();
                hasSBXH = false;
            }
        };
        sbxhCall.enqueue(callback);
    }

    private void doLoginQuery(String loginJson) {
        loginQueryCall = MyServiceUtil.loginQuery(loginJson);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                showProgress(false);
                String result = response.body();
                if (result != null) {
                    KLog.d(result);

                    Intent intent = new Intent(getApplicationContext(), SectionsListActivity.class);
                    startActivity(intent);

                } else {
                    Toast.makeText(getApplicationContext(), "获取登陆数据失败!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                showProgress(false);
                Toast.makeText(getApplicationContext(), "登陆失败：" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        };
        loginQueryCall.enqueue(callback);
    }

}
